package com.zhipu.hydration.ui.data;

import static com.zhipuchina.model.MemoryTypes.HoldingRegister;

import android.os.Bundle;
import android.text.TextUtils;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.zhipu.hydration.R;
import com.zhipu.hydration.databinding.ActivityDataBinding;
import com.zhipu.hydration.mobile.event.MessageEvent;
import com.zhipu.hydration.ui.BaseActivity;
import com.zhipuchina.event.AfterEventHandler;
import com.zhipuchina.event.EventManager;
import com.zhipuchina.model.Buffer;
import com.zhipuchina.server.ModbusTcpServer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.InetAddress;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class DataActivity extends BaseActivity<ActivityDataBinding> {

    /**
     * ModbusTcp判断
     */
    private boolean ModbusTcpJudgment = false;

    /**
     * Android 保留一位小数点
     */
    private DecimalFormat mDecimalFormat = new DecimalFormat("0.0");


    @Override
    public void initCreate() {
        super.initCreate();
        //注册，重复注册会导致崩溃
        EventBus.getDefault().register(this);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_data;

    }




    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(MessageEvent mMessageEvent) {
        switch (mMessageEvent.getType()){
            /**
             * 按键通知
             */
            case Keystroke:
                /**
                 * 误差修正
                 */
                String mErrorCorrection = SPUtils.getInstance().getString("ErrorCorrectionValue","0.0");
                /**
                 * 按键
                 */
                int mKey = mMessageEvent.getInt();
                switch (mKey){
                    case 1:
                        Bundle options = new Bundle();
                        options.putString("breed",binding.TVPZ.getText().toString());
                        //打开页面
                        ActivityUtils.startActivity(options,VarietySelectionActivity.class);
                        break;
                    case 2:

                        break;
                    case 3:
                        break;
                    case 4:
                        double subtract = Double.parseDouble(mErrorCorrection) - 0.1;
                        System.out.println("减" + subtract);
                        SPUtils.getInstance().put("ErrorCorrectionValue",String.valueOf(subtract));
                        break;
                    case 5:
                        /**
                         * 打开页面+
                         */
                        ActivityUtils.finishActivity(VarietySelectionActivity.class);
                        break;
                    case 6:
                        double add = Double.parseDouble(mErrorCorrection) + 0.1;
                        System.out.println("加" + add);
                        SPUtils.getInstance().put("ErrorCorrectionValue",String.valueOf(add));
                        break;
                    case 7:
                        //自动切换手动
                        boolean mAutomaticCacheManual = SPUtils.getInstance().getBoolean("AutomaticCacheManual",false);
                        if(mAutomaticCacheManual){
                            SPUtils.getInstance().put("AutomaticCacheManual",false);
                        }else {
                            SPUtils.getInstance().put("AutomaticCacheManual",true);
                        }
                        initData();
                        break;
                    case 8:
                        break;
                    case 9:

                        break;
                }
                /**
                 * 刷新数据
                 */
                initData();
                break;
        }
    }




    @Override
    public void initView() {
        super.initView();
        Buffer.malloc(HoldingRegister,0, 10);
        /**
         * 获取InetAddress
         */
        GetInetAddress();

    }


    @Override
    public void initData() {
        super.initData();
        /**
         * 误差修正
         */
        double ErrorCorrectionValue = Double.parseDouble(SPUtils.getInstance().getString("ErrorCorrectionValue","0.0"));
        String RoundItUp = mDecimalFormat.format(ErrorCorrectionValue);
        if(Double.parseDouble(RoundItUp) > 0.0){
            binding.AddAndSubtract.setText("+");
        }else if(Double.parseDouble(RoundItUp) == 0.0){
            binding.AddAndSubtract.setText("");
        }else {
            binding.AddAndSubtract.setText("-");
        }
        double DoubleErrorCorrectionValue = Double.parseDouble(RoundItUp);
        binding.ErrorCorrection.setText(Math.abs(DoubleErrorCorrectionValue) + "");

        /**
         * 自动切换手动
         */
        boolean mAutomaticCacheManual = SPUtils.getInstance().getBoolean("AutomaticCacheManual",false);
        if(mAutomaticCacheManual){
            binding.AutomaticCacheManual.setText("手   动");
        }else {
            binding.AutomaticCacheManual.setText("自   动");
        }
        /**
         * 误差修正
         */
        double mErrorCorrectionValue = Double.parseDouble(SPUtils.getInstance().getString("ErrorCorrectionValue","0.0"));
        LogUtils.d("mErrorCorrectionValue" + mErrorCorrectionValue);


    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        /**
         * 定时器
         */
        Observable.interval(10, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {


            }

            @Override
            public void onNext(Long aLong) {
                if(!ModbusTcpJudgment){
                    /**
                     * 获取InetAddress
                     */
                    GetInetAddress();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    /**
     * 获取InetAddress
     */
    public void GetInetAddress(){
        try {
            String hostAddress = NetworkUtils.getIPAddress(true);
            if(!TextUtils.isEmpty(hostAddress)){
                InetAddress address = InetAddress.getByName(hostAddress);
                /**
                 * 连接ModbusTcp判断
                 */
                ConnectModbusTcpJudgment(address);
            }else {
                /**
                 * ModbusTcp判断
                 */
                ModbusTcpJudgment = false;
            }
        }catch (Exception mException){
            System.out.println(mException.getMessage());
        }
    }





    /**
     * 连接ModbusTcp判断
     */
    public void ConnectModbusTcpJudgment(InetAddress mInetAddress){
        try {
            ModbusTcpServer modbusTcpServer = new ModbusTcpServer(mInetAddress, 6699);
            modbusTcpServer.start();
        }catch (Exception mException){
            /**
             * ModbusTcp判断
             */
            ModbusTcpJudgment = false;
            return;
        }
        /**
         * ModbusTcp判断
         */
        ModbusTcpJudgment = true;
        /**
         * 监听品种
         */
        EventManager.register(HoldingRegister, 0, new AfterEventHandler() {
            @Override
            public void process(int i, int i1) {
                if(i != i1){
                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            switch (i1){
                                case 0:
                                    binding.TVPZ.setText("小   麦");
                                    break;
                                case 1:
                                    binding.TVPZ.setText("玉   米");
                                    break;
                                case 2:
                                    binding.TVPZ.setText("粳   稻");
                                    break;
                                case 3:
                                    binding.TVPZ.setText("籼   稻");
                                    break;
                                case 4:
                                    binding.TVPZ.setText("大   豆");
                                    break;
                                case 5:
                                    binding.TVPZ.setText("稻   谷");
                                    break;
                            }
                        }
                    });

                }

            }
        });
        /**
         * 监听水分
         */
        EventManager.register(HoldingRegister, 1, new AfterEventHandler() {
            @Override
            public void process(int i, int i1) {
//                /**
//                 * 误差修正
//                 */
                double ErrorCorrectionValue = Double.parseDouble(SPUtils.getInstance().getString("ErrorCorrectionValue","0.0"));



                /**
                 *
                 */
                double hydration = i1 / 100.0;
                String result = String.format("%.1f",hydration);
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.hydration.setText(result);
                    }
                });
            }
        });
    }


    @Override
    protected void onDestroy() {
        //解绑
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}